<?php
/**
 * Класс Controller_Ajax_Autosuggest отвечает за обработку ajax-запросов, связанных с автозаполнением
 * @author Mike
 */
class Controller_Ajax_Autosuggest extends Controller_Ajax {

	public function actionSwitch() {
		switch ($this->arrRequest[2]) {
			case 'city' :
				$this->actionCity();
				break;
			case 'join-team' :
				$this->actionJoinTeam();
				break;
			default:
				$this->setError(404);
				break;
		}
	}

	/**
	 * Города
	 */
	private function actionCity() {
		$objDB = Service_Database::instanse();
		$nameStartWith = isset($_POST['nameStartWith']) ? Service_Escape::absolutelyEscapeString($_POST['nameStartWith']) : '';

		if (empty($nameStartWith)) return $this->makeStandardError('Не получены данные');

		$stmt = "SELECT `city`.`city_name`,`city`.`ID_city`,`city`.`city_url` FROM `city` WHERE `city`.`city_name` LIKE '%" . $nameStartWith . "%' LIMIT 5";
		$citiesArray = $objDB->select($stmt);
		$this->arrReturn = array('result' => 'OK', 'serverAnswer' => $citiesArray);
	}
	
	/**
	 * Автокомплит команд по id(на странице турниров)
	 */
	private function actionJoinTeam() {
		$objDB = Service_Database::instanse();
		$arrTeam = array();
		$idTeam = isset($_POST['nameStartWith']) ? Service_Escape::absolutelyEscapeString($_POST['nameStartWith']) : '';
	
		if (empty($idTeam)) return $this->makeStandardError('Не получены данные');
		
		if(preg_match('#^[0-9]{1,10}$#', $idTeam)) { // Если у нас число
			$stmt = "SELECT `team`.`team_name`, `team`.`ID_team`
				 FROM `team` WHERE `team`.`ID_team` ='" . $idTeam . "'";
			$arrTeam = $objDB->select($stmt);
		}
		
		$this->arrReturn = array('result' => 'OK', 'serverAnswer' => $arrTeam);
	}
}
?>